package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.FinancialAnnouncements;
import com.ruoyi.system.domain.FinancialKeyword;
import com.ruoyi.system.service.IFinancialAnnouncementsService;
import com.ruoyi.system.service.IFinancialKeywordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {

    private static final Logger log = LoggerFactory.getLogger(RyTask.class);

    @Autowired
    private IFinancialAnnouncementsService financialAnnouncementsService;


    @Autowired
    private IFinancialKeywordService iFinancialKeywordService;


    /**
     * 定时删除数据
     * @param day 删除天
     */
    public void deleteData(Integer day){
        financialAnnouncementsService.delete(day);
    }


    // MyBatis Mapper
    public void ryMultipleParams2() {
        // 基础URL，不带查询参数
        String baseUrl = "http://www.cninfo.com.cn/new/fulltextSearch/full";

        // 从服务中获取金融关键词列表
        List<FinancialKeyword> financialKeywords = iFinancialKeywordService.selectFinancialKeywordList(null);
        if (CollectionUtils.isEmpty(financialKeywords)) {
            return;  // 如果没有金融关键词，直接返回
        }

        // 提取并去重的类型名称集合，过滤掉parentId为0的记录
        Set<String> typeNameSet = financialKeywords.stream()
                .filter(t -> t.getParentId() != 0)
                .map(FinancialKeyword::getTypeName)
                .collect(Collectors.toSet());

        if (CollectionUtils.isEmpty(typeNameSet)) {
            return;  // 如果没有有效的类型名称，直接返回
        }

        // 获取当前日期，作为开始日期和结束日期
        String startDate = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);  // yyyy-MM-dd
        String endDate = startDate;  // 结束日期和开始日期相同

        // 这里示例类型是：szb, cyb, bjs, kcb, hzb，可以根据实际需求动态获取或设置
        String types = "szb,cyb,bjs,kcb,hzb";

        // 遍历每个金融关键词的类型名称进行请求
        for (String typeName : typeNameSet) {
            // 构建URL，URL编码确保字符串合法
            String url = buildUrl(baseUrl, typeName, startDate, endDate, types);

            // 发送GET请求获取响应
            String result = HttpUtils.sendGet(url);
            System.out.println(result);
            JSONObject jsonObject = JSON.parseObject(result);
            // pdf dizhi http://static.cninfo.com.cn/finalpage/2024-12-10/1221965156.PDF#navpanes=0&toolbar=0&statusbar=0&pagemode=thumbs&page=1
            if (jsonObject != null && jsonObject.getInteger("totalAnnouncement") !=0) {
                JSONArray announcements1 = jsonObject.getJSONArray("announcements");
                if (!announcements1.isEmpty()){
                    for (Object announcement : announcements1) {
                        JSONObject j = (JSONObject)announcement;
                        FinancialAnnouncements financialAnnouncements = new FinancialAnnouncements();
                        // 设置标题
                        String announcementTitle = j.getString("announcementTitle");
                        announcementTitle = announcementTitle.replaceAll("<em>|</em>", "");
                        financialAnnouncements.setF002V(announcementTitle);
                        Date announcementTime = toDate(j.getLong("announcementTime"));
                        financialAnnouncements.setRECTIME(announcementTime);
                        // 设置其他字段
                        financialAnnouncements.setF003V("http://static.cninfo.com.cn/"+j.getString("adjunctUrl"));
                        financialAnnouncements.setSECCODE(j.getString("secCode"));
                        financialAnnouncements.setSECNAME(j.getString("secName"));
                        financialAnnouncements.setTEXTID(IdUtils.simpleUUID());
                        financialAnnouncements.setCreateTime(new Date());
                        if (!isExistingAnnouncement(announcementTitle)){
                            try {
                                // 插入公告数据
                                financialAnnouncementsService.insertFinancialAnnouncements(financialAnnouncements);
                            } catch (Exception e) {
                                // 记录日志，防止某个插入失败导致整个任务失败
                                log.error("插入公告数据失败: " + announcementTitle, e);
                            }
                        }
                    }
                }

            }
        }
    }

    private Date toDate(Long announcementTimeMillis ){
        // 创建 Date 对象
        Date announcementTime = new Date(announcementTimeMillis);
        // 使用 Calendar 类来处理时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(announcementTime);

        // 获取时、分、秒
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);

        // 如果时分秒为 0，表示时间只有日期部分，赋值当前时间
        if (hour == 0 && minute == 0 && second == 0) {
            announcementTime = new Date();  // 设置为当前时间
            System.out.println("没有时分秒，已设置为当前时间: " + announcementTime);
        } else {
            System.out.println("有时分秒，使用原时间: " + announcementTime);
        }
        return announcementTime;
    }


    /**
     * 构建带参数的URL
     * @param baseUrl 基础URL
     * @param searchKey 搜索关键字
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param types 类型参数
     * @return 构建好的URL
     */
    private String buildUrl(String baseUrl, String searchKey, String startDate, String endDate, String types) {
        try {
            return baseUrl + "?searchkey=" + searchKey
                    + "&sdate=" + startDate
                    + "&edate=" + endDate
                    + "&isfulltext=false&sortName=pubdate&sortType=desc&pageNum=1&pageSize=2000&type=" + types;
        } catch (Exception e) {
            e.printStackTrace();  // 捕获编码异常并打印
            return "";  // 如果URL构建失败，返回空字符串
        }
    }

    /**
     * 验证公告是否已经存在
     */
    private boolean isExistingAnnouncement(String record) {
        LocalDate localDate = LocalDate.now();
        // 将 LocalDate 转换为 java.util.Date
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 直接返回条件判断结果，减少多余的代码
        return financialAnnouncementsService.selectF002Count(record,date) > 0;
    }


}
